package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.*;
import com.itheima.common.BaseContext;
import com.itheima.dao.AddressBookDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.ShoppingCartDao;
import com.itheima.dao.UserDao;
import com.itheima.exception.CustomException;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, Orders> implements OrderService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private AddressBookDao addressBookDao;

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Autowired
    private OrderDetailService orderDetailService;


    @Override
    public void submit(Orders order) {
        //1.从ThreadLocal中获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userDao.selectById(userId);

        //2.根据addressBookId查询用户下单地址信息 判断是否存在
        AddressBook addressBook = addressBookDao.selectById(order.getAddressBookId());
        if(addressBook==null){
            throw new CustomException("用户地址不存在！");
        }

        //3.根据用户id去购物车表中查询下单的商品数据 判断是否存在
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> carts = shoppingCartDao.selectList(shoppingCartLambdaQueryWrapper);
        if(carts==null || carts.size()==0){
            throw new CustomException("购物车中没有商品！");
        }

        //使用MyBatisPlus提供的IdWorker根据雪花算法先生成订单id
        long orderId = IdWorker.getId();
        //定义总金额  使用原子类型保证多线程数据安全
        AtomicInteger sumAmount = new AtomicInteger(0);

        //4.保存订单下的商品数据到订单详情表order_detail中
        //本质：将当前用户购物车中的商品转移到订单详情表中
        //组装订单详情信息
        List<OrderDetail> orderDetailList = carts.stream().map(cart -> {
            //a：创建订单详情信息对象
            OrderDetail orderDetail = new OrderDetail();
            //b：将购物车中的商品复制到订单详情中
            BeanUtils.copyProperties(cart,orderDetail);
            //c：设置订单id
            orderDetail.setOrderId(orderId);
            //d：计算订单总金额
            sumAmount.addAndGet((orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber())).intValue()));
            //e：返回订单详情信息对象
            return orderDetail;
        }).collect(Collectors.toList());

        orderDetailService.saveBatch(orderDetailList); //批量保存订单下的商品列表数据到订单详情表中


        //5.保存订单基本信息到订单表orders中
        //组装订单
        //订单id id;
        order.setId(orderId);
        //订单号 number;
        order.setNumber(UUID.randomUUID().toString());
        //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消 status;
        order.setStatus(2);
        //下单用户id userId;
        order.setUserId(userId);
        //地址id addressBookId; 前端已经传递
        //下单时间 orderTime;
        order.setOrderTime(LocalDateTime.now());
        //结账时间 checkoutTime;
        order.setCheckoutTime(LocalDateTime.now());
        //支付方式 1微信，2支付宝 payMethod;  前端已经传递
        //实收金额 amount;
        order.setAmount(new BigDecimal(sumAmount.get()));
        //备注 remark;  前端已经传递
        //用户名 userName;
        order.setUserName(user.getName());
        //手机号 phone;
        order.setPhone(addressBook.getPhone());
        //地址 address;
        String address = (addressBook.getProvinceName()==null?"":addressBook.getProvinceName())+
                         (addressBook.getCityName()==null?"":addressBook.getCityName())+
                         (addressBook.getDistrictName()==null?"":addressBook.getDistrictName())+
                          addressBook.getDetail();
        order.setAddress(address);
        //收货人 consignee;
        order.setConsignee(addressBook.getConsignee());

        this.save(order);

        //6.下单完成，清空当前用户购物车中的商品数据
        shoppingCartDao.delete(shoppingCartLambdaQueryWrapper);
    }
}
